package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.unit.DataUnit;

import javax.xml.crypto.Data;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

/**
 * @program: gmall-parent
 * @author: Mr.Zhuo
 * @create: 2022-04-21 10:35
 **/
@Service
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private AlipayClient alipayClient;


    /**
     * 发起退款
     *
     * @param orderId
     * @return
     */
    @Override
    public boolean refund(Long orderId) {
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();

        PaymentInfo paymentInfo = paymentInfoService.selectPaymentInfoById(orderId);

        bizContent.put("out_trade_no", paymentInfo.getOutTradeNo());
        bizContent.put("refund_amount", 0.01);
        bizContent.put("out_request_no", "HZ01RF001");

        //// 返回参数选项，按需传入
        //JSONArray queryOptions = new JSONArray();
        //queryOptions.add("refund_detail_item_list");
        //bizContent.put("query_options", queryOptions);

        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (response.isSuccess()) {
            // 进行修改 支付订单的状态哦
            PaymentInfo paymentInfo1 = new PaymentInfo();
            paymentInfo1.setId(orderId);
            paymentInfoService.updatePaymentInfoStatus(paymentInfo1, PaymentStatus.CLOSED.name());
            return true;
        } else {
            return false;
        }

    }

    /**
     * 查询订单
     * @param orderId
     * @return
     */
    @Override
    public Boolean checkPayment(Long orderId) {
        // 根据订单Id 查询订单信息
        OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        HashMap<String, Object> map = new HashMap<>();
        map.put("out_trade_no",orderInfo.getOutTradeNo());
        // 根据out_trade_no 查询交易记录
        request.setBizContent(JSON.toJSONString(map));
        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            return true;
        } else {
            return false;
        }

    }

    /**
     * 关闭订单
     * @param orderId
     * @return
     */
    @Override
    public Boolean closePay(Long orderId) {
        OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        HashMap<String, Object> map = new HashMap<>();
        // map.put("trade_no",paymentInfo.getTradeNo()); // 从paymentInfo 中获取！
        map.put("out_trade_no",orderInfo.getOutTradeNo());
        map.put("operator_id","YX01");
        request.setBizContent(JSON.toJSONString(map));

        AlipayTradeCloseResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
            return true;
        } else {
            System.out.println("调用失败");
            return false;
        }
    }

    /**
     * 生成支付宝二维码
     *
     * @param orderId
     * @return
     * @throws AlipayApiException
     */
    @Override
    public String createaliPay(Long orderId) throws AlipayApiException {

        // 根据订单id 来查询
        OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);
        // 创建二维码的同时，我们还需要进行保存数据
        paymentInfoService.savePaymentInfo(orderInfo, PaymentType.ALIPAY.name());
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest(); //创建API对应的request
        alipayRequest.setReturnUrl(AlipayConfig.return_payment_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_payment_url); //在公共参数中设置回跳和通知地址
        //alipayRequest.setBizContent("{" +
        //        "    \"out_trade_no\":\"20150320010101001\"," +
        //        "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
        //        "    \"total_amount\":88.88," +
        //        "    \"subject\":\"Iphone6 16G\"," +
        //        "    \"body\":\"Iphone6 16G\"," +
        //        "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
        //        "    \"extend_params\":{" +
        //        "    \"sys_service_provider_id\":\"2088511833207846\"" +
        //        "    }" +
        //        "  }"); //填充业务参数
        JSONObject jsonObject = new JSONObject();
        // 订单里面，我们传给支付宝一个随机，不唯一的值
        jsonObject.put("out_trade_no", orderInfo.getOutTradeNo());
        // 默认值 在官网上拿就行
        jsonObject.put("product_code", "FAST_INSTANT_TRADE_PAY");
        // 总价格
        jsonObject.put("total_amount", 0.01);
        // 消费说明
        jsonObject.put("subject", orderInfo.getTradeBody());
        // yyyy-MM-dd HH:mm:ss 首先我们需要设置时间格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE, 10);
        Date timeQB = instance.getTime();
        // 我们可以进行获取订单时间,进行跟订单时间做的对比
        Date timeOrder = orderInfo.getExpireTime();
        int compareTo = timeOrder.compareTo(timeQB);
        if (compareTo != 0) {
            if (compareTo == -1) {
                // 前者小于后者
                timeQB = timeOrder;
            }
        }

        // 设置支付宝二维码过期时间
        jsonObject.put("time_expire", simpleDateFormat.format(timeQB));

        alipayRequest.setBizContent(jsonObject.toJSONString());
        String form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
        return form;
    }
}
